from wtforms import Form
from wtforms.fields import StringField, PasswordField, IntegerField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError, NumberRange
from .base_validate import ValidateMixin, MyIntegerField
from app.constant import StoreStatus
from app.model.category_model import CategoryModel
from app.model.image_model import ImageModel


class ProductPostValidate(Form, ValidateMixin):

    name = StringField(validators=[DataRequired(message='商品名不能为空')])
    price = IntegerField(validators=[DataRequired(message='价格不能为空且不能为非整数')])
    stock = IntegerField(validators=[DataRequired(message='库存不能为空且不能为非整数')])
    imgs_id = StringField(validators=[DataRequired('图片id不能为空')])
    categorys_id = StringField(validators=[DataRequired('类别id不能为空')])
    summary = StringField(validators=[DataRequired(message='商品摘要不能为空')])

    def validate_imgs_id(self, field):
        value:str = field.data
        if not value:
            raise ValidationError('商品图片id不存在')

        ids = value.split('|')

        if len(ids) == 0:
            raise ValidationError('商品图片id不合法')
        if len(ids) > 5:
            raise ValidationError('商品图片id只能有5个')
        if not ImageModel.check_image(ids):
            raise ValidationError('商品图片id有些不存在数据库')

    def validate_categorys_id(self, field):
        category_ids = field.data
        if not category_ids:
            raise ValidationError('商品类别id不存在')

        ids = category_ids.split('|')
        print('ids', ids)
        if len(ids) == 0:
            raise ValidationError('商品类别id不合法')
        if len(ids) > 5:
            raise ValidationError('商品类别id只能有5个')
        if not CategoryModel.check_category(ids):
            raise ValidationError('商品类别id有些不存在数据库')

class ProductGetValidate(Form, ValidateMixin):

    cg = IntegerField(validators=[DataRequired(message='类型不能为空且不能为非整数')])
    p = IntegerField(validators=[DataRequired(message='页数不能为空且不能为非整数')])
    s = MyIntegerField(message='分页大小必须是数字')

    def validate_s(self, field):
        size = field.data
        if not size:
            return
        if size > 15 or size <= 0:
            raise ValidationError('分页大小不能大于15小于1')